package com.fire.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.fire.service.CommonService;
import com.fire.util.ConstantKeys;
import com.fire.util.MsgInfo;
import com.fire.util.base.ResultBody;

@Service
public class CommonServiceImpl implements CommonService {

	/**
	 * 图片上传统一接口
	 */
	@Override
	public ResultBody imageUpload(MultipartFile image) throws Exception {
		ResultBody result = new ResultBody();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String dateDir = df.format(new Date());// new Date()为获取当前系统时间
		String serviceName = "";

		if (!image.isEmpty()) {
			// 通过UUID生成上传文件名
			serviceName = UUID.randomUUID().toString().replace("-", "").toLowerCase()
					+ image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf("."));

			File tempFile = new File(ConstantKeys.IMAGE_BASE_URL + dateDir + File.separator + serviceName);
			if (!tempFile.getParentFile().exists()) {
				tempFile.getParentFile().mkdirs();
			}

			BufferedOutputStream out = null;
			try {
				// 写入文件到磁盘
				out = new BufferedOutputStream(new FileOutputStream(tempFile));
				out.write(image.getBytes());
				out.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				result.setCode(MsgInfo.z_upload_error_code);
				result.setMessage(MsgInfo.z_upload_error_msg);
				return result;
			} catch (IOException e) {
				e.printStackTrace();
				result.setCode(MsgInfo.z_upload_error_code);
				result.setMessage(MsgInfo.z_upload_error_msg);
				return result;
			} finally {
				out.close();
			}

		}
		result.setData("/image/" + dateDir + "/" + serviceName);
		return result;
	}

}
